import { createRouter, createWebHistory } from 'vue-router'
import Index from '@/views/index/Index.vue'
import Document from '@/views/document/Document.vue'
import ArticleIndex from '@/views/article/ArticleIndex.vue'
import Article from '@/views/article/Article.vue'
import Error404 from '@/views/error/Error404.vue'
import DocAccessIndex from '@/views/access/DocAccessIndex.vue'

const routes = [
  {
    path: '/',
    name: 'Index',
    component: Index
  },
  {
    path: '/document/:document_id',
    name: 'Document',
    component: Document,
    props: true
  },
  {
    path: '/articleIndex',
    name: 'ArticleIndex',
    component: ArticleIndex,
    props: true
  },
  {
    path: '/article/:id',
    name: 'Article',
    component: Article,
    props: true
  },
  {
    path: '/error404',
    name: 'Error404',
    component: Error404,
    props: true
  },
  {
    path: '/docAccessIndex',
    name: 'DocAccessIndex',
    component: DocAccessIndex,
    props: true
  },
]

const router = createRouter({
  routes,
  history: createWebHistory(),
  scrollBehavior() {
    return { top: 0 }
  }
})

router.beforeEach((to, from, next) => {
  if (to.name === 'Document') {
    const documentId = to.params.document_id
    const isNeedAccess = localStorage.getItem(`document_${documentId}`)

    // 需要密码，且未验证过密码，则跳转到验证页面

    if (isNeedAccess === 0 || isNeedAccess === '0') {
      next()
    } else {
      const accessKey = localStorage.getItem(`document_key_${documentId}`)
      if (accessKey) {
        next()
      } else {
        next({ name: 'DocAccessIndex', params: { document_id: documentId, id: to.query?.id } })
      }
    }
  } else if (to.matched.length === 0) {
    next('/Error404')
  } else {
    next()
  }
})

export default router
